package com.bankcard.bininfo.storage;

import com.bankcard.bininfo.model.BinInfo;
import com.bankcard.util.RedisClient;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class RedisBinInfoStorage implements BinInfoStorage {
    private final RedisClient redisClient;
    private final ObjectMapper objectMapper;

    public RedisBinInfoStorage(RedisClient redisClient) {
        this.redisClient = redisClient;
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public void addBinInfo(BinInfo binInfo) {
        try {
            String json = objectMapper.writeValueAsString(binInfo);
            redisClient.set("bin:" + binInfo.getBin(), json);
        } catch (Exception e) {
            throw new RuntimeException("Error adding BinInfo to Redis", e);
        }
    }

    @Override
    public BinInfo getBinInfo(String bin) {
        try {
            String json = redisClient.get("bin:" + bin);
            if (json != null) {
                return objectMapper.readValue(json, BinInfo.class);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("Error getting BinInfo from Redis", e);
        }
    }

    @Override
    public void updateBinInfo(BinInfo binInfo) {
        addBinInfo(binInfo);
    }

    @Override
    public List<BinInfo> getAllBinInfo() {
        // This method is not efficient for Redis and should be used carefully
        // You might want to implement a different approach for bulk operations
        throw new UnsupportedOperationException("getAllBinInfo is not supported for Redis storage");
    }
}